<?php

namespace App\Http\Admin\v1\Controllers;

use App\Http\Admin\v1\Controllers\BasesController;
use App\Models\Admin;
use App\Models\AdminGroup;
use App\Models\Group;
use App\Services\AdminServices;
use App\Services\GroupServices;
use App\Util\VerifyRequest;
use Illuminate\Http\Request;
use App\Util;
use App\Util\Code;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use PhpParser\Node\Expr\New_;


class AdminController extends BasesController
{
    use VerifyRequest;
    protected $only = ['update','delete','create','delete','ceshi',''];

    /**
     * 获取用户列表
     * @param  Request  $request
     * @return JsonResponse
     */
    public function lists( Request $request )
    {
        $columns = ['nick_name','user_name','mobile','status','created_at'];

        $list = AdminServices::getInstance()->listAdmins( $request, $columns);

        return $this ->succ($list);
    }
    /**
     * 创建用户
     * @param  Request  $request
     * @return JsonResponse
     */
    public function create( Request $request )
    {

        //参数验证
        $username   = $this -> checkTitle('username');
        $mobile     = $this -> checkMobile('mobile');
        $email      = $this -> checkEmail('email');
        $groupIds   = $request -> input("group_ids");

        //检测此用户是否存在不存在创建用户
        $user = AdminServices::getInstance()->getByUser( $username );
        if ( !is_null($user) ) {
            return $this->fail(Code::AUTH_NAME_REGISTERED);
        }

        $user = AdminServices::getInstance()->getByMobile( $mobile );
        if ( !is_null($user) ) {
            return $this->fail(Code::AUTH_NAME_REGISTERED);
        }


        DB::beginTransaction();
        // 写入用户表
        $user = new Admin();
        $user -> user_name     = $username;
        $user -> nick_name     = $username;
        $user -> password      = Hash::make('12345678');
        $user -> mobile        = $mobile;
        $user -> email         = $email;
        $user -> last_ip = $request->getClientIp();
        $user -> status        = 1;

        if ( !$user->save()){
            DB::rollBack();
            return $this ->fail(Code::FAIL);
        }

        //写入用户分组对应表
        if ( !empty($groupIds) ){

            //查询用户传递分组是否存在
            $groupInfo = GroupServices::getInstance()->getByGroups( $groupIds );

            //更新用户分组对应关系
            $group = GroupServices::getInstance()->CreateByAdminGroup($user->id,$groupIds);

            if ( !$group ){

                DB::rollBack();
                return $this ->fail(Code::FAIL);
            }

        }

        DB::commit();

        return $this ->succ();
    }
    /**
     * 获取图片验证码
     * @param  Request  $request
     * @return JsonResponse
     */
    public function captcha()
    {
        $data = $this->CreateCaptcha(4);
        return $this->succ( $data );
    }
    /**
     * 登录
     * @param  Request  $request
     * @return JsonResponse
     */
    public function login( Request $request )
    {

        //获取账号密码
        $username = $request->input('username');
        $password = $request->input('password');
        //数据验证
        if (empty( $username ) || empty( $password ) ) {
            return $this->fail(Code::CLT_ILLEGAL,"用户名或密码不得为空");
        }

        $key     = $this->checkPubTitle("key",null,Code::CLT_ILLEGAL);
        $captcha = $this->checkPubTitle("captcha",null,Code::CLT_ILLEGAL);

        //取出缓存中存放的验证码
        $captcha = \Cache::get( $key );
        if ( strtolower( $key ) != strtolower( $captcha ) ){
           return $this ->fail(code::Wx_CAPTCHA_ILLEGAL );
        }

        //验证账号是否存在
        $user = AdminServices::getInstance()->getByUser($username);
        if (is_null($user)) {
            return $this->fail(Code::AUTH_INVALID_ACCOUNT);
        }

        //对密码进行验证
        $isPass = Hash::check($password, $user->getAuthPassword());
        if (!$isPass) {
            return $this->fail(Code::AUTH_INVALID_ACCOUNT, '账号密码不正确');
        }

        //更新登录的信息
        $user->last_ip = $request->getClientIp();
        if ( !$user->save() ) return $this->fail(Code::UPDATED_FAIL);

        //获取token
        $token = Auth::guard('admin')->login($user);

        //组装数据并返回
        return $this->succ([
            'token' => $token,
            'user_info' => $user
        ]);
    }
    /*
     * 获取个人信息
     * */
    public function  Info()
    {

        //验证账号是否存在
//        if ( empty($id) ){
// //
//            return $this ->fail(Code::UPDATED_FAIL  ,'传递参数不得为空');
//        }
//


//        $user = AdminServices::getInstance()->getByUserId(1);
//        if (is_null($user)) {
//            return $this->fail(Code::AUTH_INVALID_ACCOUNT);
//        }
//        return $this->succ([
//            'user_info'=>$user,
//        ]);
//


        $arr = array('code' => 20000, 'data'=>array('roles' =>  array('admin'), 'introduction' => '我是一个管理员', 'avatar' => 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif','name' => 'Super Admin','token' => 'admin'));
        //$arr = array('code' => 50008, 'message' =>  'Account and password are incorrect.');
        echo json_encode($arr);






//        $data=[
//            'roles'=>array('admin',222),
//
//            'name'=>'张骞',
//            'avatar'=>'11',
//            'introduction'=>'简介'
//        ];
//        $data=json_encode($data,true);
//        return $this->succ($data);
//
//
//        $user = Auth::guard('admin')->user();
//
//        return $this ->succ([
//            'user_info'=>$user
//        ]);

    }
public function ceshi(){

    $user = Auth::guard('admin')->user();

    return $this ->succ([
        'info'=>$user
    ]);

}
    /**
     * 修改个人信息
     * @param  Request  $request
     * @return JsonResponse
     */
    public function update(Request $request , $id ){

        if ( empty( $id ) ) return $this->fail(Code::CLT_ILLEGAL,"Id不得为空");

        //修改用户信息
        $password   = $request -> input('password');
        $groupIds    = $request -> input("group_ids");


        DB::beginTransaction();

        //检测此用户是否存在
        $user = AdminServices::getInstance()->getByUserId( $id );
        if ( is_null($user) ) {
            return $this->fail(Code::AUTH_INVALID_ACCOUNT);
        }

        // 写入用户表
        $user -> password      = Hash::make( $password );
        if ( !$user->save()){

            DB::rollBack();
            return $this ->fail(Code::FAIL);
        }

        if ( !empty( $groupIds ) ){

            //验证分组是否存在
            $group = GroupServices::getInstance()->UpdateByAdminGroup($id,$groupIds);
            if ( !$group ){

                DB::rollBack();
                return $this ->fail(Code::FAIL);
            }
        }


        DB::commit();

        return $this ->succ();


    }
    /**
     * 删除用户
     * @param  Request  $request
     * @return JsonResponse
     */
    public function delete( Request $request , $id )
    {
        if ( empty( $id ) ) return $this->fail(Code::CLT_ILLEGAL,"删除编号不得为空");

        //验证账号是否存在
        $user = AdminServices::getInstance()->getByUserId($id);
        if (is_null($user)) {
            return $this->fail(Code::AUTH_INVALID_ACCOUNT);
        }
        DB::beginTransaction();

        $admin = Admin::find( $id )->delete();

        if( !$admin ){
            DB::rollBack();
            return $this ->fail(Code::FAIL);
        }

        $group = GroupServices::getInstance()->getByAdminGroupId($id);
        if (!is_null($group)) {

            //获取用户分组关系
            $group = AdminGroup::where('admin_id', $id)->delete();


            if( !$group ){
                DB::rollBack();
                return $this ->fail(Code::FAIL);
            }
        }

        DB::commit();

        return $this->succ();

    }
    public function  logout()
    {
        Auth::guard('admin')->logout();
        return $this->succ();
    }


}
